package com.eascs.crm.nsEditDetail.service;

import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.eascs.admin.common.vo.ModelResult;
import com.eascs.admin.o2o.loan.dao.O2oLoanUserDao;
import com.eascs.admin.o2o.loan.entity.O2oLoanUserEntity;
import com.eascs.app.dao.PageResult;
import com.eascs.app.log.Logger;
import com.eascs.app.log.LoggerFactory;
import com.eascs.crm.nsEditDetail.dao.CustomerInfoDao;
import com.eascs.crm.nsEditDetail.entity.CustOpLogEntity;
import com.eascs.crm.nsEditDetail.entity.CustomerAssetInfo;
import com.eascs.crm.nsEditDetail.entity.CustomerBasicEntity;
import com.eascs.crm.nsEditDetail.entity.CustomerShopInfoEntity;
import com.eascs.crm.nsEditDetail.vo.CustomerBasicVo;
import com.eascs.crm.nsEditDetail.vo.LoanBaseInfoVO;
import com.eascs.crm.nsEditDetail.vo.O2oLoanUserVo;
import com.eascs.web.sso.User;
import com.eascs.web.sso.UserHolder;

@Service
public class CustomerInfoService {
	private static Logger logger = LoggerFactory.getLogger(CustomerInfoService.class);

	@Autowired
	CustomerInfoDao customerDao;
	
	@Autowired
	CustOpLogService custOpLogService;
	@Autowired
	O2oLoanUserDao o2oLoanUserDao;
	
	@Transactional(transactionManager = "o2oTransactionManager")
	public ModelResult<CustomerBasicEntity> saveEntity(CustomerBasicEntity entity) {
		ModelResult<CustomerBasicEntity> modelResult =new ModelResult<>();
		entity.setDataSource("1");
		User user = UserHolder.getUser();
		if (user != null) {
			entity.setCreator(user.getCname());
			entity.setCreate_id(user.getNo());
			entity.setModifier(user.getCname());
			entity.setModify_id(user.getNo());
			entity.setCreate_date(new Date());
			entity.setModify_date(new Date());
		}
		boolean result = customerDao.saveEntity(entity);
		if(!result){
			return modelResult.withError(null,"插入失败");
		}
		try {
			
			CustOpLogEntity custOpLogEntity =new CustOpLogEntity();
			custOpLogEntity.setOpPsn(entity.getCreator());
			custOpLogEntity.setOpId(entity.getLoan_user_id());
			custOpLogEntity.setOpType(CustOpLogEntity.INSERT_OP_TYPE);
			custOpLogService.saveLog(custOpLogEntity, entity);
		} catch (Exception e) {
			logger.info("客户修改日志异常:[{}]", e);
		}
		modelResult.setModel(entity);
		return modelResult;
	}
	
	@Transactional(transactionManager = "o2oTransactionManager")
	public ModelResult<CustomerBasicEntity> udpateEntity(CustomerBasicEntity entity, O2oLoanUserVo o2oLoanUserVo) {
		ModelResult<CustomerBasicEntity> modelResult =new ModelResult<>();
		CustomerBasicEntity  sourceEntity =customerDao.queryCustomerBasicById(entity.getLoan_user_id());
		sourceEntity.setHome_phone(entity.getHome_phone());
		sourceEntity.setPostcode(entity.getPostcode());
		sourceEntity.setAccount_county(entity.getAccount_county());
		sourceEntity.setAccount_city(entity.getAccount_city());
		sourceEntity.setAccount_province(entity.getAccount_province());
		sourceEntity.setPermanent_residence(entity.getPermanent_residence());
		sourceEntity.setRecipient_province(entity.getRecipient_province());
		sourceEntity.setRecipient_county(entity.getRecipient_county());
		sourceEntity.setRecipient_city(entity.getRecipient_city());
		sourceEntity.setRecipient_address(entity.getRecipient_address());
		sourceEntity.setLive_years(entity.getLive_years());
		sourceEntity.setChildren_info(entity.getChildren_info());
		sourceEntity.setOther_info_desc(entity.getOther_info_desc());
		sourceEntity.setIssuing_authority(entity.getIssuing_authority());
		sourceEntity.setLicense_expiration_date(entity.getLicense_expiration_date());
		sourceEntity.setEducation(entity.getEducation());
		sourceEntity.setWechat(entity.getWechat());
		sourceEntity.setBorrower_census_register(entity.getBorrower_census_register());
		sourceEntity.setWork_unit(entity.getWork_unit());
		
		 sourceEntity.setMarryDate(entity.getMarryDate());
		
	
		sourceEntity.setDivorceDate(entity.getDivorceDate());
		
		User user = UserHolder.getUser();
		if (user != null) {
			sourceEntity.setModifier(user.getCname());
			sourceEntity.setModify_id(user.getNo());
			sourceEntity.setModify_date(new Date());
		}
		boolean result = customerDao.udpateEntity(sourceEntity);
		O2oLoanUserEntity o2oLoanUserEntity = customerDao.getById(O2oLoanUserEntity.class, entity.getLoan_user_id());
		o2oLoanUserEntity.setUserNamePinyin(o2oLoanUserVo.getSurnamePinyin()+o2oLoanUserVo.getNamePinyin());
		o2oLoanUserEntity.setSurnamePinyin(o2oLoanUserVo.getSurnamePinyin());
		o2oLoanUserEntity.setNamePinyin(o2oLoanUserVo.getNamePinyin());
		o2oLoanUserEntity.setUserPhone(o2oLoanUserVo.getUserPhone());
		customerDao.updateById(o2oLoanUserEntity);
		if(!result){
			return modelResult.withError(null,"修改失败");
		}
		try {
			
			CustOpLogEntity custOpLogEntity =new CustOpLogEntity();
			custOpLogEntity.setOpPsn(entity.getModifier());
			custOpLogEntity.setOpId(entity.getLoan_user_id());
			custOpLogEntity.setOpType(CustOpLogEntity.UPDATE_OP_TYPE);
			custOpLogService.saveLog(custOpLogEntity, entity);
		} catch (Exception e) {
			logger.info("客户修改日志异常:[{}]", e);
		}
		modelResult.setModel(entity);
		return modelResult;
	}
	
	public CustomerBasicVo queryCustomerById(String loanUserId,String spouseId) {
		if (StringUtils.isBlank(loanUserId)) {
			return null;
		}
		CustomerBasicVo customer = customerDao.queryCustomerById(loanUserId);
		if (StringUtils.isBlank(spouseId)) {
			return customer;
		}
		CustomerBasicVo spouse = customerDao.queryCustomerById(spouseId);
		if (customer == null) {
			customer = new CustomerBasicVo();

		}
		customer.setSpouse(spouse);

		return customer;
	}
	
	/**
	 * @Title: sychCustomerInfo
	 * @Description:根据身份证同步最新客户上次贷款信息
	 * @author 张庆奇
	 * @param loanUserId
	 *            现在的user表主键
	 * @param idcard
	 * @return void
	 * @throws @date
	 *             2017年8月2日 上午10:39:15
	 */
	public void sychCustomerInfo(String loanUserId, String loanapplyNo, String idcard) {
		// 1.根据身份证查询客户最新贷款信息(上一笔借款人的信息)
		CustomerBasicVo sourceEntity = customerDao.queryCustomerByIdNum(loanUserId, idcard);
		if (sourceEntity == null)
			return;
		// 2.更新借款人的剩余信息
		CustomerBasicEntity entity = customerDao.queryCustomerBasicById(loanUserId);
		entity = copy(sourceEntity, entity);
		customerDao.udpateEntity(entity);
		logger.info("客户扩展信息修改:[{}]", entity.getCreate_id());
		//3.添加借款人门店信息
		String sql = "SELECT * FROM customer_shop_info t WHERE t.loanapply_no=?  AND t.islock='N'";
		List<CustomerShopInfoEntity> shopList= customerDao.findEntitys(sql, CustomerShopInfoEntity.class, sourceEntity.getLoanapply_no());
		if(!shopList.isEmpty()&&shopList.size()>0){
			for (CustomerShopInfoEntity shopEntity : shopList) {
				shopEntity.setCustomerShopId(null);
				shopEntity.setDataSource("1");
				shopEntity.setLoanapplyNo(loanapplyNo);
				customerDao.insert(shopEntity);
			}
			
		}
		logger.info("添加借款人门店信息完成loanapplyNo:[{}]",sourceEntity.getLoanapply_no());
		//4.添加借款人资产信息
		String asset_sql = "SELECT * FROM customer_asset_info t WHERE t.loanapply_no=? ";
		CustomerAssetInfo asset=customerDao.findEntity(asset_sql, CustomerAssetInfo.class, sourceEntity.getLoanapply_no());
		if(asset!=null){
			asset.setLoanapplyNo(loanapplyNo);
			
			customerDao.insert(asset);
		}
		logger.info("添加借款人资产信息完成");
		
		// 5.如果现在借款人存在配偶信息，更新配偶的其他信息
		if (entity.getMarital_status() == 2) {

			// 现在配偶userID
			String mateUserId = o2oLoanUserDao.findMateUserEntity(loanapplyNo);
			if (StringUtils.isNotBlank(mateUserId)) {
				// 现在配偶扩展表信息
				CustomerBasicEntity mateEntity = customerDao.queryCustomerBasicById(mateUserId);
				// 上一笔配偶偶userID
				String mateSourceUserId = o2oLoanUserDao.findMateUserEntity(sourceEntity.getLoanapply_no());
				if (StringUtils.isNotBlank(mateSourceUserId)) {
					// 上一笔配偶扩展表信息
					CustomerBasicVo mateSourceEntity = customerDao.queryCustomerById(mateSourceUserId);

					mateEntity = copy(mateSourceEntity, mateEntity);
					customerDao.udpateEntity(mateEntity);
				}
			}
			logger.info("更新配偶人信息完成");
		}

	}

	/**
	 * @Title: copy
	 * @Description: 从一个对象复制信息到另一个对象
	 * @author 张庆奇
	 * @param sourceEntity
	 * @param entity
	 * @return
	 * @return CustomerBasicEntity
	 * @throws @date
	 *             2017年8月2日 下午1:30:02
	 */
	public CustomerBasicEntity copy(CustomerBasicVo sourceEntity, CustomerBasicEntity entity) {
		entity.setAge(sourceEntity.getAge());
		entity.setPostcode(sourceEntity.getPostcode());
		entity.setWork_unit(sourceEntity.getWork_unit());
		entity.setWechat(sourceEntity.getWechat());
		entity.setBorrower_census_register(sourceEntity.getBorrower_census_register());
		entity.setAccount_county(sourceEntity.getAccount_county());
		entity.setAccount_city(sourceEntity.getAccount_city());
		entity.setAccount_province(sourceEntity.getAccount_province());
		entity.setPermanent_residence(sourceEntity.getPermanent_residence());
		entity.setIssuing_authority(sourceEntity.getIssuing_authority());
		entity.setEducation(sourceEntity.getEducation());
		entity.setHome_phone(sourceEntity.getHome_phone());
		entity.setRecipient_county(sourceEntity.getRecipient_county());
		entity.setRecipient_city(sourceEntity.getRecipient_city());
		entity.setRecipient_province(sourceEntity.getRecipient_province());
		entity.setRecipient_address(sourceEntity.getRecipient_address());
		entity.setLive_years(sourceEntity.getLive_years());
		entity.setChildren_info(sourceEntity.getChildren_info());
		entity.setOther_info_desc(sourceEntity.getOther_info_desc());
		return entity;
	}
	
	/**
	 * @Title: findCustomerOrMateLoan
	 * @Description: 根据贷款贷款客户id.配偶id，查询客户贷款详细信息
	 * @author LMX
	 * @param vo
	 * @return
	 * @return PageResult<Object[]>
	 * @throws
	 * @data 2017.8.16
	 */
	public PageResult<Object[]> findCustomerOrMateLoan(LoanBaseInfoVO vo) {
		return customerDao.findloanerAndMateLoan(vo);
	}
	
	/**
	 * @Title: updateCustomerBasicHyrq
	 * @Description: 修改借款人婚姻日期
	 * @author 张庆奇
	 * @param entity
	 * @return void
	 * @throws
	 * @date 2018年1月9日 下午7:29:47
	 */
	public void updateCustomerBasicHyrq(CustomerBasicEntity entity){
		String excuteSql="" ;
		
		if(entity.getMarryDate()!=null){
			excuteSql="update customer_basic_info set marry_date=? where loan_user_id=?" ;
			 customerDao.execute(excuteSql, entity.getMarryDate(),entity.getLoan_user_id());
		}
		if(entity.getDivorceDate()!=null){
			excuteSql="update customer_basic_info set divorce_date=? where loan_user_id=?" ;
			 customerDao.execute(excuteSql, entity.getDivorceDate(),entity.getLoan_user_id());
		}

	}
	
}

